package com.cema.manage.project.manage.users.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cema.manage.common.utils.StringUtils;
import com.cema.manage.framework.aspectj.lang.annotation.Log;
import com.cema.manage.framework.web.controller.BaseController;
import com.cema.manage.framework.web.domain.Message;
import com.cema.manage.framework.web.page.TableDataInfo;
import com.cema.manage.project.enums.UserStatusEnum;
import com.cema.manage.project.manage.userDailyActivity.service.IUserDailyActivityService;
import com.cema.manage.project.manage.users.domain.Users;
import com.cema.manage.project.manage.users.service.IUsersService;
import com.cema.manage.project.system.post.domain.Post;
import com.cema.manage.project.system.post.service.IPostService;
import com.cema.manage.project.system.role.domain.Role;
import com.cema.manage.project.system.role.mapper.RoleMapper;
import com.cema.manage.project.system.role.service.IRoleService;
import com.cema.manage.project.system.user.domain.User;
import com.cema.manage.project.system.user.service.IUserService;
import com.google.gson.Gson;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;


/**
 * 用户信息
 *
 * @author reasahi
 */
@Controller
@RequestMapping("/manage/userAgent")
public class UserAgentController extends BaseController {

    private String prefix = "manage/userAgent";

    @Autowired
    private IUserService userService;

    @Resource
    private RoleMapper roleMapper;
    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPostService postService;

    @Resource
    private IUsersService usersService;

    @Resource
    private IUserDailyActivityService userDailyActivityService;

    @RequiresPermissions("manage:userAgent:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions("manage:userAgent:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user) {
        startPage();
        user.setManageIndex(2);
        List<User> list = userService.selectUserList(user);
        if (ObjectUtil.isNull(list)) {
            return getDataTable(list);
        }
        EntityWrapper<Users> entityWrapper = new EntityWrapper<>();
        entityWrapper.isNotNull("kickback");
        List<Users> usersList = usersService.selectList(entityWrapper);
        for (User userResult : list) {
            Optional<Users> usersResult = usersList.stream().filter(users -> userResult.getPlUserId().equals(users.getId())).findFirst();
            userResult.setKickback(usersResult.get().getKickback());
        }
        return getDataTable(list);
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("manage:userAgent:edit")
    @Log(title = "系统管理", action = "用户管理-修改用户")
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, Model model) {
        User user = userService.selectUserById(userId);
        Users users = usersService.selectById(user.getPlUserId());
        user.setKickback(users.getKickback());
        List<Role> roles = roleService.selectRolesByUserId(userId);
        List<Role> userRoles = roleMapper.selectRolesByUserId(userId);
        boolean flag = false;
        if (userRoles != null && userRoles.size() > 0) {
            for (Role m : userRoles) {
                if (m.getRoleId() == 4l) {
                    flag = true;
                }
            }
        }
        List<Post> posts = postService.selectPostsByUserId(userId);
        model.addAttribute("roles", roles);
        model.addAttribute("posts", posts);
        model.addAttribute("user", user);
        model.addAttribute("flag", flag);
        return prefix + "/edit";
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("manage:userAgent:add")
    @Log(title = "系统管理", action = "用户管理-新增用户")
    @GetMapping("/add")
    public String add(Model model) {
        List<Role> roles = roleService.selectRoleAll();
        List<Post> posts = postService.selectPostAll();
        model.addAttribute("roles", roles);
        model.addAttribute("posts", posts);
        return prefix + "/add";
    }

    @RequiresPermissions("manage:userAgent:resetPwd")
    @Log(title = "系统管理", action = "用户管理-重置密码")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, Model model) {
        User user = userService.selectUserById(userId);
        model.addAttribute("user", user);
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("manage:userAgent:resetPwd")
    @Log(title = "系统管理", action = "用户管理-重置密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    public Message resetPwd(User user) {
        int rows = userService.resetUserPwd(user);
        if (rows > 0) {
            return Message.success();
        }
        return Message.error();
    }

    /**
     * 保存用户
     */
    @RequiresPermissions("manage:userAgent:save")
    @Log(title = "系统管理", action = "用户管理-保存用户")
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public Message save(User user) {
        Users users = usersService.selectById(user.getPlUserId());
        if (ObjectUtil.isNull(users)) {
            return Message.error("代理用户ID不存在");
        }
        if (UserStatusEnum.USER_STATUS_VIOLATION.getValue().equals(users.getStatus())) {
            return Message.error("代理用户ID违规封号");
        }
        user.setDeptId(103L);
        user.setRoleIds(new Long[]{4L});
        user.setPostIds(new Long[]{2L});

        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return Message.error("不允许修改超级管理员用户");
        }
        return userService.saveUser(user) > 0 ? Message.success() : Message.error();
    }


    /**
     * 保存用户
     */
    @RequiresPermissions("manage:userAgent:save")
    @Log(title = "系统管理", action = "用户管理-保存用户")
    @PostMapping("/status")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public Message saveStatus(User user) {
        return userService.updateUser(user) > 0 ? Message.success() : Message.error();
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(User user) {
        String uniqueFlag = "0";
        if (user != null) {
            uniqueFlag = userService.checkLoginNameUnique(user.getLoginName());
        }
        return uniqueFlag;
    }


    @RequiresPermissions("manage:userAgent:trafficObservation")
    @Log(title = "系统管理", action = "用户管理-修改用户")
    @GetMapping("/traffic_observation")
    public String trafficObservation(HttpServletRequest request, Model model) {
        String currentTime = request.getParameter("currentTime");
        Gson gson = new Gson();
        model.addAttribute("currentTime", StrUtil.isNotEmpty(currentTime) ? currentTime : null);
        model.addAttribute("userDailyActivityList", gson.toJson(userDailyActivityService.getUserDailyActivity(currentTime)));
        return prefix + "/traffic_observation";
    }
}